package com.biu.billiards.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.biu.billiards.config.BaseErrorEnum;
import com.biu.billiards.config.BaseException;
import com.biu.billiards.mapper.ShopMapper;
import com.biu.billiards.model.Login.WxLoginVo;
import com.biu.billiards.model.bo.UserBO;
import com.biu.billiards.model.entity.Goods;
import com.biu.billiards.model.entity.Shop;
import com.biu.billiards.model.entity.User;
import com.biu.billiards.mapper.UserMapper;
import com.biu.billiards.model.vo.jsApiPay.GetApiPlayVo;
import com.biu.billiards.model.vo.mqtt.OpenBilliardsVo;
import com.biu.billiards.model.vo.shop.orderAdmin.AddOrderAdminVo;
import com.biu.billiards.model.vo.user.AddUserVo;
import com.biu.billiards.model.vo.user.GetUserVo;
import com.biu.billiards.model.vo.user.UpdateUserVO;
import com.biu.billiards.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.biu.billiards.utils.RedisUtils;
import com.biu.billiards.utils.TokenUtils;
import com.ijpay.core.kit.PayKit;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xue
 * @since 2023-09-25
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    @Resource
    private IGoodsService goodsService;

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private UserMapper userMapper;


    @Resource
    private ShopMapper shopMapper;
    @Resource
    private IBilliardsService billiardsService;

    @Resource
    private IShopService shopService;

    @Resource
    private IUserService userService;


    @Resource
    private IOrderService orderService;
    @Override
    public UserBO getInfo(WxLoginVo wxLoginVo, HttpServletRequest request) {

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("open_id",wxLoginVo.getOpenId());
        User user = userMapper.selectOne(queryWrapper);

        UserBO userDetailBO = new UserBO();
        BeanUtils.copyProperties(user,userDetailBO);


        return userDetailBO;
    }

    @Override
    public User getUser(Integer userId) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        return userMapper.selectOne(queryWrapper);

    }

    @Override
    public UserBO wxLogin(WxLoginVo wxLoginVo) {

        if (wxLoginVo.getKey()==null || !wxLoginVo.getKey().equals(DigestUtils.md5Hex("qweqwrqw12asdmryy"+wxLoginVo.getCode()+"asffgiifaruoifiuahof")
        )){
            throw new BaseException(BaseErrorEnum.SIGNATURE_NOT_MATCH);
        }
        System.out.println("wxLoginVo");

        System.out.println(wxLoginVo);
        //查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("open_id",wxLoginVo.getOpenId());
        User user = userMapper.selectOne(queryWrapper);

       if (user!=null){

            UserBO userDetailBO = new UserBO();
            BeanUtils.copyProperties(user,userDetailBO);
            String token= TokenUtils.sign(wxLoginVo.getCode());
            redisUtils.set("token--"+wxLoginVo.getCode(),token,3, TimeUnit.DAYS);
            userDetailBO.setToken(token);

            return userDetailBO;

        }else {

           User user1 = new User();
           user1.setPhone(wxLoginVo.getPhone());
           user1.setOpenId(wxLoginVo.getOpenId());
           user1.setCreateTime(LocalDateTime.now());

            if (userMapper.insert(user1)==1){
                UserBO userDetailBO = new UserBO();
                String token= TokenUtils.sign(wxLoginVo.getCode());
                redisUtils.set("token--"+wxLoginVo.getCode(),token,3, TimeUnit.DAYS);
                userDetailBO.setToken(token);

                return userDetailBO;

            }else {

                throw new BaseException(BaseErrorEnum.USER_NOT_EXISTS);
            }

        }


    }



    @Override
    public IPage<UserBO> getUserPage(GetUserVo getUserVo) {
        QueryWrapper<User> query = new QueryWrapper<>();


        System.out.println("getUserVo");
        System.out.println(getUserVo);


        if (getUserVo.getPhone()!=null){
            query.like("phone",getUserVo.getPhone());
        }

        if (getUserVo.getUserType()!=null){
            query.eq("user_type",getUserVo.getUserType());
        }

        if (getUserVo.getVipStatus()!=null){
            query.eq("vip_status",getUserVo.getVipStatus());
        }

        //新建分页条件
        Page<User> p = new Page<>(getUserVo.getCurrentPage(),getUserVo.getPageSize());
        IPage<User> userIPage = userMapper.selectPage(p,query);
        IPage<UserBO> page = new Page<>();
        List<UserBO> adminDetailBOList = new ArrayList<>();
        for (User admin: userIPage.getRecords()){
            UserBO adminDetailBO = new UserBO();
            BeanUtils.copyProperties(admin,adminDetailBO);
            adminDetailBOList.add(adminDetailBO);
        }
        /* 将转化的BO放到的Records里面  */
        page.setRecords(adminDetailBOList);
        page.setCurrent(userIPage.getCurrent());
        page.setPages(userIPage.getPages());
        page.setPages(userIPage.getSize());
        page.setTotal(userIPage.getTotal());

        return page;
    }

    @Override
    public Boolean updateUser(UpdateUserVO updateUserVO) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",updateUserVO.getUserId());
        User user = userMapper.selectOne(queryWrapper);

        BeanUtils.copyProperties(updateUserVO,user);

//        user.setUserBalance(updateUserVO.getUserBalance());
//        user.setPhone(updateUserVO.getPhone());
//        user.setVipStatus(updateUserVO.getVipStatus());
//
//        user.setShopId(updateUserVO.getShopId());



        return userMapper.update(user, queryWrapper) == 1;
    }

    @Override
    public Boolean addUser(AddUserVo addUserVo) {
        User user = new User();
        BeanUtils.copyProperties(addUserVo,user);

        addUserVo.setCreateTime(LocalDateTime.now());

        return userMapper.insert(user) == 1;
    }

    @Override
    public Boolean updateUserWith(Integer userId, Integer userType) {


        if (userType==1){

            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id",userId);
            User user = userMapper.selectOne(queryWrapper);

            user.setWallet(new BigDecimal(0));

            return userMapper.update(user, queryWrapper) == 1;


        }else if (userType==2){

            QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("shop_id",userId);
            Shop shop = shopMapper.selectOne(queryWrapper);

            shop.setWallet(new BigDecimal(0));

            return shopMapper.update(shop, queryWrapper) == 1;

        }



        return false;
    }





    @Override
    public Boolean addWallet(Integer userId, BigDecimal price) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        User user = userMapper.selectOne(queryWrapper);

        user.setWallet(user.getWallet().add(price));

        return userMapper.update(user, queryWrapper) == 1;

    }




    @Override
    public Boolean deleteUser(Integer userId) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        return userMapper.delete(queryWrapper) == 1;
    }



    @Override
    public Boolean userBalanceLack(GetApiPlayVo getApiPlayVo) {

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", getApiPlayVo.getUserId());

        User user = userMapper.selectOne(queryWrapper);

        Goods goods = goodsService.selectGoods(getApiPlayVo.getGoodsId());

       if (user.getUserBalance().compareTo(goods.getGoodsPrice())> -1){

           return true;

       }else {

           return false;
       }


    }

    @Override
    public Boolean payBalance(GetApiPlayVo getApiPlayVo) {


        if (billiardsService.getBilliardsOpenStatus(getApiPlayVo.getBilliardsId())){
            throw new BaseException(BaseErrorEnum.OPEN_ERROR);
        }

        Goods goods = goodsService.selectGoods(getApiPlayVo.getGoodsId());
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", getApiPlayVo.getUserId());
        User user = userMapper.selectOne(queryWrapper);

        BigDecimal payPrice = goods.getGoodsPrice();


        if (user.getVipStatus().equals("2")){

            payPrice= new BigDecimal(goods.getV1());

        }else if (user.getVipStatus().equals("3")){

            payPrice= new BigDecimal(goods.getV2());

        }


        if (user.getUserBalance().compareTo(payPrice)> -1){

           // goods.getGoodsPrice();

            user.setUserBalance(user.getUserBalance().subtract(payPrice));

            userMapper.update(user, queryWrapper);

            System.out.println("余额足");


            AddOrderAdminVo addOrderVo = new AddOrderAdminVo();
            addOrderVo.setPhone(getApiPlayVo.getPhone());
            addOrderVo.setOrderId(PayKit.generateStr());
            addOrderVo.setUserId(user.getUserId());
            addOrderVo.setGoodsName(goods.getGoodsName());
            addOrderVo.setGoodsPrice(payPrice);
            addOrderVo.setPlayWay("余额支付");
            addOrderVo.setCreateTime(LocalDateTime.now());
            addOrderVo.setGoodsId(getApiPlayVo.getGoodsId());
            addOrderVo.setBilliardsNumber(getApiPlayVo.getBilliardsNumber());
            addOrderVo.setDeviceNumber(getApiPlayVo.getDeviceNumber());
            addOrderVo.setBilliardsId(getApiPlayVo.getBilliardsId());
            addOrderVo.setOrderStatus(1);
            addOrderVo.setOrderType(1);
            addOrderVo.setActualPrice(payPrice);
            addOrderVo.setBilliardsHour(goods.getPlayHour());
            addOrderVo.setStartTime(LocalDateTime.now());
            addOrderVo.setEndTime(LocalDateTime.now().plusHours(goods.getPlayHour()));
            addOrderVo.setShopId(getApiPlayVo.getShopId());





            //余额支付
//            addOrderVo.setShopActualSum(new BigDecimal(1));
//            addOrderVo.setRecommendActualSum(new BigDecimal(1));
//            addOrderVo.setPlatformActualSum(new BigDecimal(1));



            //余额支付  1 年费 2 分成
            Shop shop = shopService.getShop(getApiPlayVo.getShopId());

            if (shop!=null){
                addOrderVo.setRecommendId(shop.getRecommendId());
                addOrderVo.setFeeType(shop.getFeeType());

                if (getApiPlayVo.getFeeType()==1){


                    addOrderVo.setRecommendActualSum(new BigDecimal(0));
                    addOrderVo.setPlatformActualSum(new BigDecimal(0));
                    addOrderVo.setShopActualSum(payPrice.multiply(new BigDecimal(0.994)));


                    shopService.addWallet(shop.getShopId(),payPrice.multiply(new BigDecimal(0.994)));



                } else if (getApiPlayVo.getFeeType()==2) {


                    BigDecimal recommendActualSum = payPrice.multiply(new BigDecimal(0.005964));
                    BigDecimal platformActualSum = payPrice.multiply(new BigDecimal(0.023856));
                //    BigDecimal shopActualSum = payPrice.subtract(recommendActualSum).subtract(platformActualSum);

                    BigDecimal shopActualSum = payPrice.multiply(new BigDecimal(0.96418));


                    addOrderVo.setShopActualSum(shopActualSum);
                    addOrderVo.setRecommendActualSum(recommendActualSum);
                    addOrderVo.setPlatformActualSum(platformActualSum);


                    userService.addWallet(shop.getRecommendId(),recommendActualSum);

                    shopService.addWallet(shop.getShopId(),shopActualSum);



                }

            }



            //余额支付  1 年费 2 分成
//            if (getApiPlayVo.getFeeType()!=null){
//
//                addOrderVo.setFeeType(getApiPlayVo.getFeeType());
//
//                if (getApiPlayVo.getFeeType()==1){
//
//
//                    addOrderVo.setRecommendActualSum(new BigDecimal(0));
//                    addOrderVo.setPlatformActualSum(new BigDecimal(0));
//                    addOrderVo.setShopActualSum(payPrice.multiply(new BigDecimal(0.94)));
//
//
//                } else if (getApiPlayVo.getFeeType()==2) {
//
//
//                    BigDecimal recommendActualSum = payPrice.multiply(new BigDecimal(0.00564));
//                    BigDecimal platformActualSum = payPrice.multiply(new BigDecimal(0.02256));
//                    BigDecimal shopActualSum = payPrice.subtract(recommendActualSum).subtract(platformActualSum);
//
//
//                    addOrderVo.setShopActualSum(shopActualSum);
//                    addOrderVo.setRecommendActualSum(recommendActualSum);
//                    addOrderVo.setPlatformActualSum(platformActualSum);
//
//
//
//                }
//
//
//
//            }



//            if (getApiPlayVo.getRecommendId()!=null){
//                addOrderVo.setRecommendId(getApiPlayVo.getRecommendId());
//            }

           // addOrderVo.setBilliardsHour(hours);

            orderService.addOrder(addOrderVo);


            //开台
            OpenBilliardsVo openBilliardsVo = new OpenBilliardsVo();
            openBilliardsVo.setBilliardsNumber(addOrderVo.getBilliardsNumber());
            openBilliardsVo.setDeviceNumber(addOrderVo.getDeviceNumber());
            openBilliardsVo.setBilliardsId(addOrderVo.getBilliardsId());
            openBilliardsVo.setHour(addOrderVo.getBilliardsHour());
            openBilliardsVo.setOpen(1);
            openBilliardsVo.setShopId(getApiPlayVo.getShopId());
             openBilliardsVo.setHardwareId(getApiPlayVo.getHardwareId());

            billiardsService.openBilliards(openBilliardsVo);

           return true;

        }else {

            System.out.println("余额不足");

            return false;
        }


    }


    @Override
    public Boolean userTopUp(GetUserVo getUserVo) {

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", getUserVo.getUserId());
        User user = userMapper.selectOne(queryWrapper);
        user.setUserBalance(user.getUserBalance().add(getUserVo.getPayPrice()));


        if (getUserVo.getPayPrice().compareTo(new BigDecimal(200)) == 0 && user.getVipStatus().equals("1")) {

            user.setVipStatus("2");

        } else if (getUserVo.getPayPrice().compareTo(new BigDecimal(500)) == 0 && !user.getVipStatus().equals("3")){

            user.setVipStatus("3");
        }


        return userMapper.update(user, queryWrapper) == 1;

    }

    @Override
    public Boolean topUp(GetUserVo getUserVo) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", getUserVo.getUserId());
        User user = userMapper.selectOne(queryWrapper);
        user.setUserBalance(user.getUserBalance().add(getUserVo.getPayPrice()));

        if (userMapper.update(user, queryWrapper)==1){
            AddOrderAdminVo addOrderAdminVo = new AddOrderAdminVo();

            addOrderAdminVo.setOrderId(user.getShopId());
            addOrderAdminVo.setOrderStatus(1);
            addOrderAdminVo.setCreateTime(LocalDateTime.now());
            addOrderAdminVo.setGoodsName("管理员充值");
            addOrderAdminVo.setOrderType(2);
            addOrderAdminVo.setOrderId(PayKit.generateStr());
            addOrderAdminVo.setPlayWay("充值");
            addOrderAdminVo.setPayPrice(getUserVo.getPayPrice());

            addOrderAdminVo.setUserId(user.getUserId());

           return orderService.topUpOrder(addOrderAdminVo);

        }else {

            return false;
        }








    }


}
